<template>
  <a-modal
    width="80vw"
    :visible="visible"
    :title="data.title"
    :mask-closable="false"
    unmount-on-close
    ok-text="完成对账"
    cancel-text="关闭"
    @before-open="handleBeforeOpen"
    @cancel="handleCancel"
    @close="handleClose"
    @before-ok="handleBeforeOk"
  >
    <div style="max-height: 78vh">
      <a-tabs default-active-key="1">
        <a-tab-pane key="1" title="对账费项">
          <table-index :table="tableData" @loadData="loadData">
            <template #orderCode="{ record }">
              <div class="order-info-item">
                <div>自有</div>
                <div>{{ record.orderCode }}</div>
              </div>
              <div class="order-info-item" v-if="record.channelOrderCode">
                <div>{{ record.channelTypeName }} {{ record.channelOrderCode }}</div>
              </div>
            </template>
            <template #memberInfo="{ record }">
              <div>{{ record.memberName }}</div>
              <div>{{ record.memberPhone }}</div>
            </template>
            <template #remark="{ record }">
              <span class="flex flex-col">
                <span class="w-full flex-1 text">{{ record.remark || '-' }}</span>
                <div class="remark-btn" v-if="record.remark" @click="showRemarkModal(record)">查看更多</div>
              </span>
            </template>
          </table-index>
        </a-tab-pane>
        <a-tab-pane key="2" title="结算信息">
          <table-index :table="table" @loadData="loadData" size="mini">
            <template #orderCode="{ record }">
              <div class="order-info-item">
                <div>自有</div>
                <div>{{ record.orderCode }}</div>
              </div>
              <div class="order-info-item" v-if="record.channelOrderCode">
                <div>{{ record.channelTypeName }} {{ record.channelOrderCode }}</div>
              </div>
            </template>
            <template #settlementInfo="{ record }">
              <div>{{ record.settlementUserName }}</div>
              <div>{{ record.settlementTime }}</div>
            </template>
          </table-index>
        </a-tab-pane>
      </a-tabs>

      <page-form :model="form" ref="formRef" class="mt-4 custom-w">
        <card title="对账信息" :showDivider="false">
          <page-form-row gutter="24">
            <page-form-item label="对账总额" size="1">
              <div class="font-extrabold">{{ unitVal(totalAmount) }}</div>
            </page-form-item>
          </page-form-row>
          <page-form-row gutter="24">
            <page-form-item
              label="对账时间"
              size="1"
              field="billTime"
              :rules="[{ required: true, message: '请选择对账时间', trigger: 'change' }]"
            >
              <i-date-picker class="w-full" v-model="form.billTime" show-time value-format="YYYY-MM-DD HH:mm:ss" popup-container="#app" />
            </page-form-item>
          </page-form-row>
          <page-form-row gutter="24">
            <page-form-item label="流水号" size="1" field="serialNo">
              <a-input v-model="form.serialNo" placeholder="请输入" :maxlength="50" />
            </page-form-item>
          </page-form-row>
          <page-form-row gutter="24">
            <page-form-item label="对账备注" size="1" field="remark">
              <a-input v-model="form.remark" placeholder="请输入" :maxlength="200" />
            </page-form-item>
          </page-form-row>
          <page-form-row gutter="24">
            <page-form-item label="上传凭证" size="1" field="fileIdList">
              <upload-img v-model="form.fileIdList" :limit="5" />
            </page-form-item>
          </page-form-row>
        </card>
      </page-form>
    </div>
  </a-modal>

  <!-- 备注列表弹框 -->
  <remark-log-modal ref="remarkModalRef" />
</template>

<script setup lang="ts">
  import remarkLogModal from './remark-log-modal.vue'

  import { computed, ref } from 'vue'
  import { useTable } from '@/hooks/table'
  import { getShortOrderBillFeeList, getShortOrderBillSettlementDetail, completeShortOrderBill } from '@/api/finance/examine'
  import decimal from '@/utils/calculation'
  import { setTableRowSpan } from '@/utils/table-row-span'
  import { unitVal } from '@/utils'
  import { Message } from '@arco-design/web-vue'
  import dayjs from 'dayjs'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default: () => ({}),
    },
  })

  const emits = defineEmits(['update:modelValue', 'ok'])
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emits('update:modelValue', value),
  })

  const tableData = useTable({
    pagination: false,
    size: 'mini',
    columns: [
      { title: '订单号', dataIndex: 'orderCode', slotName: 'orderCode', fixed: 'left', width: 150 },
      { title: '车牌号', dataIndex: 'carLicenseNo', width: 100 },
      { title: '承租人信息', dataIndex: 'memberInfo', slotName: 'memberInfo', width: 110 },
      { title: '费用名称', dataIndex: 'itemName', width: 90 },
      { title: '操作节点', dataIndex: 'createNodeName', width: 90 },
      { title: '费用类型', dataIndex: 'feeTypeName', width: 90 },
      { title: '收支类型', dataIndex: 'costTypeName', width: 90 },
      { title: '总额', dataIndex: 'amount', unit: '元', width: 80 },
      { title: '实结', dataIndex: 'payAmount', unit: '元', width: 80 },
      { title: '未结', dataIndex: 'waitPayAmount', unit: '元', width: 80 },
      { title: '已对账', dataIndex: 'billedAmount', unit: '元', width: 90 },
      { title: '本次对账金额', dataIndex: 'settlementAmount', unit: '元', width: 130 },
      { title: '费用备注', slotName: 'remark', width: 100 },
    ],
    spanMethod: (data: { record: any; column: any; rowIndex: number; columnIndex: number }) => {
      const { record, column } = data
      if (record.mergeCell?.includes(column.dataIndex)) {
        const rowspan = record[`rowspan_${column.dataIndex}`]
        if (rowspan) {
          return { rowspan: rowspan, colspan: 1 }
        } else {
          return { rowspan: 0, colspan: 0 }
        }
      }
    },
  })

  const table = useTable({
    pagination: false,
    size: 'mini',
    columns: [
      { title: '订单号', dataIndex: 'orderCode', slotName: 'orderCode', fixed: 'left', width: 150 },
      { title: '车牌号', dataIndex: 'carLicenseNo', width: 100 },
      { title: '费用名称', dataIndex: 'itemName', width: 90 },
      { title: '结算总额', dataIndex: 'settlementAmount', unit: '元', width: 110 },
      { title: '结算方式', dataIndex: 'payTypeName', width: 110 },
      { title: '结算人及时间', slotName: 'settlementInfo', width: 110 },
      { title: '结算账号', dataIndex: 'account', width: 100 },
      { title: '收付款客户姓名', dataIndex: 'customerName', width: 130 },
      { title: '客户结算账号', dataIndex: 'customerAccount', width: 110 },
      { title: '结算备注', dataIndex: 'settlementRemark', width: 100 },
    ],
    spanMethod: (data: { record: any; column: any; rowIndex: number; columnIndex: number }) => {
      const { record, column } = data
      if (record.mergeCell?.includes(column.dataIndex)) {
        const rowspan = record[`rowspan_${column.dataIndex}`]
        if (rowspan) {
          return { rowspan: rowspan, colspan: 1 }
        } else {
          return { rowspan: 0, colspan: 0 }
        }
      }
    },
  })

  const formRef = ref()
  const form = ref<any>({})
  const totalAmount = ref(0)

  // 获取对账明细
  const getReconciliationList = (idList: string[] | number[]) => {
    // 需要合并的字段名，按照合并登记来排序
    const colFields = ['orderCode', 'carLicenseNo', 'memberInfo']

    return new Promise((resolve, reject) => {
      getShortOrderBillFeeList({ idList })
        .then((res: any) => {
          const result: any[] = []
          res.result.forEach((item: any) => {
            item.feeDetailList.forEach((feeItem: any) => {
              const settlementAmount = decimal.sub(feeItem.payAmount || 0, feeItem.billedAmount || 0)
              result.push({
                ...item,
                settlementAmount,
              })
              if (feeItem.costType == 10) {
                totalAmount.value = decimal.add(totalAmount.value, settlementAmount)
              } else if (feeItem.costType == 20) {
                totalAmount.value = decimal.sub(totalAmount.value, settlementAmount)
                console.log('totalAmount1', feeItem.itemName, feeItem.costType, totalAmount.value, settlementAmount)
              }
            })
          })

          console.log('totalAmount2', totalAmount.value)

          let feeDetailListLength = 0
          let j = 0
          for (let i = 0; i < result.length; i++) {
            feeDetailListLength = result[i].feeDetailList.length
            for (j; j < result[i].feeDetailList.length; j++) {
              result[i] = {
                ...result[i],
                ...result[i].feeDetailList[j],
              }
              j++
              if (j == feeDetailListLength) {
                j = 0
              }
              break
            }
          }

          /** 遍历需要合并单元格 */
          setTableRowSpan(result, colFields)
          resolve(result)
        })
        .catch((err: any) => {
          reject(err)
        })
    })
  }

  // 获取结算明细
  const getSettlementList = (orderFeeIdList: string[] | number[]) => {
    // 需要合并的字段名，按照合并登记来排序
    const colFields = ['orderCode', 'carLicenseNo']

    return new Promise((resolve, reject) => {
      getShortOrderBillSettlementDetail({ orderFeeIdList })
        .then((res: any) => {
          const result: any[] = []
          res.result.forEach((item: any) => {
            item.feeSettlementList.forEach(() => {
              result.push({
                ...item,
              })
            })
          })

          let feeDetailListLength = 0
          let j = 0
          for (let i = 0; i < result.length; i++) {
            feeDetailListLength = result[i].feeSettlementList.length - 1

            if (j > feeDetailListLength) {
              j = 0
            }

            for (j; j < result[i].feeSettlementList.length; j++) {
              result[i] = {
                ...result[i],
                ...result[i].feeSettlementList[j],
              }
              j++
              break
            }
          }

          /** 遍历需要合并单元格 */
          setTableRowSpan(result, colFields)
          resolve(result)
        })
        .catch((err: any) => {
          reject(err)
        })
    })
  }

  /**
   * @param idList 订单费项id列表
   */
  const loadData = (idList: string[] | number[]) => {
    // 本次对账金额总额
    tableData.tableLoading = true

    getReconciliationList(idList)
      .then((res: any) => {
        tableData.dataList = res
      })
      .finally(() => {
        tableData.tableLoading = false
      })

    table.tableLoading = true
    getSettlementList(idList)
      .then((res: any) => {
        table.dataList = res
      })
      .finally(() => {
        table.tableLoading = false
      })
  }

  const remarkModalRef = ref()
  const showRemarkModal = (item: any) => {
    remarkModalRef.value.show(item.id, 'remark')
  }

  const handleBeforeOk = (done: (closed: boolean) => void) => {
    formRef.value.validate((valid: boolean) => {
      if (!valid) {
        completeShortOrderBill({
          idList: Array.isArray(props.data.id) ? props.data.id : [props.data.id],
          billTime: form.value.billTime,
          serialNo: form.value.serialNo,
          remark: form.value.remark,
          fileIdList: form.value.fileIdList,
          operateType: props.data.operateType,
        })
          .then(() => {
            visible.value = false
            Message.success('对账完成')
            emits('ok')
            done(true)
          })
          .catch(() => {
            done(false)
          })
      } else {
        done(false)
      }
    })
  }

  const handleCancel = () => {
    visible.value = false
  }

  const handleClose = () => {
    totalAmount.value = 0
    formRef.value.resetFields()
  }

  const handleBeforeOpen = () => {
    loadData(Array.isArray(props.data.id) ? props.data.id : [props.data.id])
    form.value = {
      billTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    }
  }
</script>

<style scoped lang="less">
  .color-1890ff {
    color: #1890ff;
  }

  .custom-w {
    width: 420px;
  }

  .border-none {
    &::before {
      content: none !important;
    }
  }

  .remark-btn {
    color: #1890ff;
    cursor: pointer;
  }

  .text {
    white-space: nowrap; /* 防止文本换行 */
    overflow: hidden; /* 隐藏溢出文本 */
    text-overflow: ellipsis; /* 使用省略号截断溢出文本 */
  }
</style>
